import axios from "axios";
import { Message, Loading } from "element-ui";
import router from "./router";
let loading;

function startLoading() {
  loading = Loading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });
}

function endLoading() {
  loading.close();
}

//请求拦截
axios.interceptors.request.use(
  (config) => {
    startLoading();

    //设置同一的请求头
    if (localStorage.token) {
      config.headers.Authorization = localStorage.token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截
axios.interceptors.response.use(
  (response) => {
    endLoading();
    return response;
  },
  (error) => {
    endLoading();
    //Message.error(error.message + "：token失效，请重新登录");
    const status = error.response.status;
    if (status == 401) {
      //console.log("token失效");
      //token失效
      Message.error("token失效，请重新登录");
      //清除token信息并跳转到登录页面
      localStorage.removeItem("token");
      //window.location.href = "/login";
      router.push("/login");
    }

    return Promise.reject(error);
  }
);

export default axios;
